package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Orders;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.exception.CustomException;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RequestMapping("/order")
@RestController
public class OrderController {

    @Autowired
    private OrderService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders order) {
        //1.调用service完成业务处理
        ordersService.submit(order);

        //2.返回下单成功
        return R.success("下单成功！");
    }

    /*//最新订单查询
    @GetMapping("/userPage")
    public R userPage(Integer page, Integer pageSize) {

        IPage<OrdersDto> pages = ordersService.getPage(page, pageSize);

        return R.success(pages);
    }*/
    @GetMapping("/userPage")
    public R<Page<Orders>> page(Integer page, Integer pageSize){
        Long userId = BaseContext.getCurrentId();
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,userId);
        ordersService.page(ordersPage,wrapper);
        return R.success(ordersPage);
    }
    @GetMapping("/page")
    public R<Page<Orders>> page2(Integer page,Integer pageSize){
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        ordersService.page(ordersPage);
        return R.success(ordersPage);
    }
    @PutMapping
    public R<Integer> update(@RequestBody Orders orders){
        if (orders.getStatus()>3){
            throw new CustomException("订单已完成,无需派送");
        }
        orders.setStatus(4);
        ordersService.updateById(orders);
        return R.success(orders.getStatus());
    }
}
